package com.gulimall.product.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.gulimall.common.utils.PageUtils;
import com.gulimall.common.utils.Query;
import com.gulimall.common.utils.R;
import com.gulimall.product.dao.SkuInfoDao;
import com.gulimall.product.entity.SkuImagesEntity;
import com.gulimall.product.entity.SkuInfoEntity;
import com.gulimall.product.feign.SeckillFeignService;
import com.gulimall.product.service.*;
import com.gulimall.product.vo.SeckillSkuInfoVo;
import com.gulimall.product.vo.SkuItemVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;


@Service("skuInfoService")
public class SkuInfoServiceImpl extends ServiceImpl<SkuInfoDao, SkuInfoEntity> implements SkuInfoService {
    @Autowired
    private SpuInfoDescService spuInfoDescService;
    @Autowired
    private SkuImagesService skuImagesService;
    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;
    @Autowired
    private AttrAttrgroupRelationService attrgroupRelationService;
    @Autowired
    private ThreadPoolExecutor poolExecutor;
    @Autowired
    private SeckillFeignService seckillFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SkuInfoEntity> page = this.page(new Query<SkuInfoEntity>().getPage(params),
                new QueryWrapper<SkuInfoEntity>());

        return new PageUtils(page);
    }

    @Override
    public void saveSkuInfo(SkuInfoEntity skuInfoEntity) {
        save(skuInfoEntity);
    }

    @Override
    public PageUtils querySkuInfoByCondition(Map<String, Object> params) {
        QueryWrapper<SkuInfoEntity> queryWrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        if (StringUtils.hasText(key)) {
            queryWrapper.and(w -> {
                w.eq("sku_id", key).or().like("sku_name", key);
            });
        }
        String catelogId = (String) params.get("catelogId");
        if (StringUtils.hasText(key) && !"0".equals(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        String brandId = (String) params.get("brandId");
        if (StringUtils.hasText(key) && !"0".equals(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }
        String min = (String) params.get("min");
        if (StringUtils.hasText(min) && !"0".equals(min)) {
            try {
                BigDecimal decimal = new BigDecimal(min);
                queryWrapper.ge("price", decimal);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        String max = (String) params.get("max");
        if (StringUtils.hasText(max) && !"0".equals(max)) {
            try {
                BigDecimal decimal = new BigDecimal(max);
                queryWrapper.le("price", decimal);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        IPage<SkuInfoEntity> iPage = this.page(new Query<SkuInfoEntity>().getPage(params), queryWrapper);
        return new PageUtils(iPage);
    }

    /**
     * 根据skuId获取对应商品的详情
     *
     * @param skuId
     * @return
     */
    @Override
    public SkuItemVO getSkuItemInfo(Long skuId) {
        SkuItemVO skuItemVo = new SkuItemVO();

        // 使用CompletableFuture 异步编排
        CompletableFuture<SkuInfoEntity> skuInfoFuture = CompletableFuture.supplyAsync(() -> {
            //1.sku的基本属性
            SkuInfoEntity skuInfo = getById(skuId);
            skuItemVo.setSkuInfo(skuInfo);
            return skuInfo;
        }, poolExecutor);

        CompletableFuture<Void> skuSaleAttrFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            //3.spu对应的所有sku的销售属性
            skuItemVo.setSaleAttrVos(skuSaleAttrValueService.getSkuSaleAttrs(res.getSpuId()));
        }, poolExecutor);

        CompletableFuture<Void> spuInfoDescFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            //4.spu的介绍
            skuItemVo.setSpuInfoDesc(spuInfoDescService.getById(res.getSpuId()));
        }, poolExecutor);

        CompletableFuture<Void> attrGroupFuture = skuInfoFuture.thenAcceptAsync((res) -> {
            //5.获取spu的规格参数
            List<SkuItemVO.SpuItemAttrGroupVo> attrGroupVoList = attrgroupRelationService.getSpuAttrs(res.getSpuId());
            skuItemVo.setAttrGroupVos(attrGroupVoList);
        }, poolExecutor);

        CompletableFuture<Void> imageFuture = CompletableFuture.runAsync(() -> {
            //2.sku的图片信息
            skuItemVo.setImages(skuImagesService.list(new QueryWrapper<SkuImagesEntity>().eq("sku_id", skuId)));
        }, poolExecutor);

        CompletableFuture<Void> seckillFuture = CompletableFuture.runAsync(() -> {
            R seckillResult = seckillFeignService.getSeckillBySkuId(skuId);
            if (seckillResult.getResult() == 0) {
                SeckillSkuInfoVo seckillSku = JSONObject.parseObject((String) seckillResult.get("seckillSku"),
                        SeckillSkuInfoVo.class);
                skuItemVo.setSeckillSkuInfoVo(seckillSku);
            }
        }, poolExecutor);

        //等待以上线程全部执行完
        try {
            CompletableFuture.allOf(skuInfoFuture, spuInfoDescFuture, imageFuture, skuSaleAttrFuture, attrGroupFuture
                    , seckillFuture).get();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return skuItemVo;
    }

    @Override
    public Map<Long, BigDecimal> getSkusPrice(List<Long> skuIds) {
        List<SkuInfoEntity> skuInfoEntities = listByIds(skuIds);
        return skuInfoEntities.stream().collect(Collectors.toMap(SkuInfoEntity::getSkuId, SkuInfoEntity::getPrice));
    }

}
